package router

import (
	"admin/controller"
	"admin/middleware"
	"io/ioutil"
	"strings"

	"github.com/gin-gonic/gin"
)

func InitRouter(app *gin.Engine) {
	// 主页
	app.NoRoute(func(c *gin.Context) {
		accept := c.Request.Header.Get("Accept")
		flag := strings.Contains(accept, "text/html")
		if flag {
			content, err := ioutil.ReadFile("www/index.html")
			if (err) != nil {
				c.Writer.WriteHeader(404)
				c.Writer.WriteString("Not Found")
				return
			}
			c.Writer.WriteHeader(200)
			c.Writer.Header().Add("Accept", "text/html")
			c.Writer.Write((content))
			c.Writer.Flush()
		}
	})

	api := app.Group("/api/")
	// 加载cors跨域中间件
	api.Use(middleware.Cors)
	// 用户验证
	api.Use(middleware.Auth)
	// 加载cors跨域中间件
	app.Use(middleware.Cors)
	{
		// 学生管理
		api.POST("/student", controller.AddStudent)
		api.GET("/student", controller.GetStudent)
		api.DELETE("/student", controller.DelStudent)
		api.PUT("/student", controller.PutStudent)

		// 系部管理
		api.POST("/department", controller.AddDepartment)
		api.GET("/department", controller.GetDepartment)
		api.DELETE("/department", controller.DelDepartment)
		api.PUT("/department", controller.PutDepartment)

		// 班级管理
		api.POST("/classes", controller.AddClasses)
		api.GET("/classes", controller.GetClasses)
		api.DELETE("/classes", controller.DelClasses)
		api.PUT("/classes", controller.PutClasses)

		// 获取数量
		api.GET("/counts", controller.GetCounts)
		// 根据类型获取
		api.POST("/count_from_type", controller.GetCountFromType)
		// 根据类型获取所有数据
		api.POST("/count_all_from_type", controller.GetAllCountFormType)
	}
	app.POST("/api/login", controller.Login)
}
